<?php
class BusinessController extends AppController
{
	public $name = "Business";

	public $components = array('PasswordGenerator', 'Image', 'MyEmail');
	public $uses = array('State', 'Plan', 'User', 'Business', 'Account', 'Category');



	public function advertise()
	{
	    self::set(array('quicksearch' => 1, 'bodywidth' => 650, 'islogin' => 0));
	}

    public function login()
    {
        self::set(array('quicksearch' => 1, 'bodywidth' => 650, 'islogin' => 1));
    }

	public function register($adsType = '')
	{
	    if (count($this->data['register']) > 0) {

            App::import('Sanitize');
            $sanitize = new Sanitize();

            // check if keywords exists
            if (!$this->data['register']['keywords']) {
                $pos = (strpos($this->data['register']['keywords'], ","));
                if ($pos === false) {
                    self::set('alert', 'Invalid keyword format');
                    self::redirect('/business/register/'.$adsType);
                }
                $key = explode(",", $this->data['register']['keywords']);
                if (count($key) <= 10) {
                    self::set('alert', 'Keyword should not exceed more than 10');
                    self::redirect('/business/register/'.$adsType);
                }
            }


            //  generate random passwords
            $password = $this->PasswordGenerator->generate();
            $this->Session->write('random', $password);

            // prepare user details for saving
            $userInfo = array('lastname' => $this->data['register']['lastname'],
                              'firstname' => $this->data['register']['firstname'],
                              'email' => $this->data['register']['email_address'],
                              'password' => sha1($password),
                              'password_confirmation' => sha1($password),
                              'date_registered' => date('Y-m-d H:i:s'),
                              'projectId' => $this->Session->read('projectId'),
                              'group_id' => 2);


            $userInfoSave = $this->User->_save(0, $userInfo);

            if ($userInfoSave) {

                $keywords = explode(", ", $this->data['register']['keywords']);
                switch ($adsType) {
                    case "premium":
                        // check website
                        $pos = strpos($this->data['register']['website'], "http://");
                        if ($pos === false) {
                            $this->data['register']['website'] = "http://" . $this->data['register']['website'];
                        }

                        // upload the file
                        $image_path = $this->Image->upload_image_and_thumbnail($this->data['register'],"name1",573,80,"logo",true);
                        $category = $this->data[category1].",".$this->data[category2].",".$this->data[category3].",".$this->data[category4].",".$this->data[category5].",".$this->data[category6];

                        $data = array('lastname' => $sanitize->escape($this->data['register']['lastname']),
                                      'firstname' => $sanitize->escape($this->data['register']['firstname']),
                                      'email_address' => $sanitize->escape($this->data['register']['email_address']),
                                      'name' => $sanitize->escape($this->data['register']['business_name']),
                                      'keyword' => self::extractKeywords($keywords, 20),
                                      'category' => $sanitize->escape($category),
                                      'description' => $sanitize->escape($this->data['register']['description']),
                                      'street' => $sanitize->escape($this->data['register']['street']),
                                      'city' => $sanitize->escape($this->data['register']['city']),
                                      'state' => $sanitize->escape($this->data['state']),
                                      'zip_code' => $sanitize->escape($this->data['register']['zipcode']),
                                      'contact_no' => $sanitize->escape($this->data['register']['business_phone']),
                                      'contact_person' => $sanitize->escape($this->data['register']['contact_person']),
                                      'website' => $sanitize->escape($this->data['register']['website']),
                                      'logo' => $image_path,
                                      'projectId' => $this->Session->read('projectId'),
                                      'active' => 1
                                      );
                        break;

                    case "enhanced":
                        $category = $this->data[category1].",".$this->data[category2].",".$this->data[category3];
                        $data = array('lastname' => $sanitize->escape($this->data['register']['lastname']),
                                      'firstname' => $sanitize->escape($this->data['register']['firstname']),
                                      'email_address' => $sanitize->escape($this->data['register']['email_address']),
                                      'name' => $sanitize->escape($this->data['register']['business_name']),
                                      'keyword' => self::extractKeywords($keywords, 20),
                                      'category' => $sanitize->escape($category),
                                      'description' => $sanitize->escape($this->data['register']['description']),
                                      'street' => $sanitize->escape($this->data['register']['street']),
                                      'city' => $sanitize->escape($this->data['register']['city']),
                                      'state' => $sanitize->escape($this->data['state']),
                                      'zip_code' => $sanitize->escape($this->data['register']['zipcode']),
                                      'contact_no' => $sanitize->escape($this->data['register']['business_phone']),
                                      'contact_person' => $sanitize->escape($this->data['register']['contact_person']),
                                      'website' => $sanitize->escape($this->data['register']['website']),
                                      'projectId' => $this->Session->read('projectId'),
                                      'active' => 1
                                      );
                        break;

                    case "basic":
                        $category = $this->data[category1].",".$this->data[category2];
                        $data = array('lastname' => $sanitize->escape($this->data['register']['lastname']),
                                      'firstname' => $sanitize->escape($this->data['register']['firstname']),
                                      'email_address' => $sanitize->escape($this->data['register']['email_address']),
                                      'name' => $sanitize->escape($this->data['register']['business_name']),
                                      'keyword' => self::extractKeywords($keywords, 20),
                                      'category' => $sanitize->escape($category),
                                      'description' => $sanitize->escape($this->data['register']['description']),
                                      'street' => $sanitize->escape($this->data['register']['street']),
                                      'city' => $sanitize->escape($this->data['register']['city']),
                                      'state' => $sanitize->escape($this->data['state']),
                                      'zip_code' => $sanitize->escape($this->data['register']['zipcode']),
                                      'contact_no' => $sanitize->escape($this->data['register']['business_phone']),
                                      'contact_person' => $sanitize->escape($this->data['register']['contact_person']),
                                      'projectId' => $this->Session->read('projectId'),
                                      'active' => 1
                                      );
                        break;
                }

                // save business details
                $businessInfo = $this->Business->_save(0, $data);
                if ($businessInfo) {
                    $accountData = array('user_id' => $userInfoSave,
                                         'plan_id' => $this->Plan->get_plan_id($adsType, $this->Session->read('projectId')),
                                         'projectId' => $this->Session->read('projectId'),
                                         'active' => 1
                                         );

                    $accountInfo = $this->Account->_save(0, $accountData);
                    if ($accountInfo) {
                        $updateInfo = array('plan_id' => $this->Plan->get_plan_id($adsType, $this->Session->read('projectId')));
                        $this->Business->_save($businessInfo, $updateInfo);

                        // send registration thank you email
                        $data = array('lastname' => $sanitize->escape($this->data['register']['lastname']),
                                      'firstname' => $sanitize->escape($this->data['register']['firstname']),
                                      'email' => $sanitize->escape($this->data['register']['email']),
                                      'wbtitle' => $this->Session->read('wbtitle'));

                        $this->MyEmail->to = $sanitize->escape($this->data['register']['email_address']);
                        $this->MyEmail->subject = $this->Session->read('wbtitle') . " Registration";
                        $this->MyEmail->from = $this->Session->read('reply_to');
                        $this->MyEmail->data = $data;

                        if (!$this->MyEmail->send()) {
                            self::set('alert', 'Error in sending registration email');
                        }

                        //  redirect page to payment if $adsType not basic
                        if ($adsType == 'basic') {
                            self::redirect('/business/advertise');
                        } else {
                            /**
                             * TODO: implement notify_url, and add procedure once
                             *       tnxid is returned.
                             */
                            self::redirect("/business/payment/".$adsType."/".$this->data['register']['email_address']);

                        }
                    }
                } else {
                    self::redirect('/business/register/'.$adsType);
                }
            } else {
                self::set('alert', 'Invalid user registration');
            }

            self::set('alert', null);
	    } else {
	        self::set('alert', 'Invalid user registration');
	    }

	    $categories = $this->Category->myGenerateList("select * from `categories`", null, 'Category.name ASC', null,'{n}.Category.name', '{n}.Category.name', ' ');
		$states = $this->State->myGenerateList("select * from `states`", null, 'State.name ASC', null,'{n}.State.name', '{n}.State.name', ' ');
		self::set(array('quicksearch' => 1, 'bodywidth' => 650, 'islogin' => 0, 'states' => $states, 'adsType' => $adsType, 'categories' => $categories));
	}

	public function payment($adsType, $email)
	{
	    // current project
	    $projectId = $this->Session->read('projectId');

	    // plan details
        $item = $this->Plan->get_plan($adsType, $projectId);
        $fee = $this->Plan->get_plan_fee($adsType, $projectId);

        // template flag
        switch ($this->Session->read('projectId')) {
            case 1:
                break;

            case 2:
                self::set('bodywidth', 650);
                self::set('quicksearch', 1);
                break;
        }

        // template parameters
        self::set(array('item' => $item, 'fee' => $fee, 'islogin' => 0, 'email' => $email));
	}

	private function extractKeywords($raw, $count)
	{
        if (!is_array($raw)) return null;
        $first = true;
        for ($i=0; count($raw)<=$count; $i++) {

            if ($first) {
                $first = false;
            } else {
                $keywords = ", ";
            }

            $keywords .= $raw[$i];

        }

        return $keywords;
	}
}
?>